<?php

namespace Bete\Exception;

use Exception as BaseException;
use Bete\Foundation\Application;
use Bete\Contract\ExceptionHandler as ExceptionHandlerContract;
use Bete\View\View;
use Bete\Log\Log;

class Handler implements ExceptionHandlerContract
{
    protected $app;

    protected $dontReport = [];

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function report(BaseException $e)
    {
        if ($this->shouldntReport($e)) {
            return;
        }

        Log::error($e);
    }

    public function shouldntReport(BaseException $e)
    {
        $dontReport = array_merge(
            $this->dontReport, ['Bete\Exception\Http3Exception']);

        foreach ($dontReport as $exception) {
            if ($e instanceof $exception) {
                return true;
            }
        }

        return false;
    }

    public function renderForConsole(BaseException $e)
    {
        return $this->renderConsoleException($e);
    }

    public function renderConsoleException(BaseException $e)
    {
        echo $e->getMessage() . "\n";
        echo "Stack trace:\n";
        echo $e->getTraceAsString() . "\n";
    }

    public function renderForHttp(BaseException $e)
    {
        if (app()->request->acceptsJson()) {
            return $this->renderJsonException($e);
        } else {
            return $this->renderHtmlException($e);
        }
    }

    public function renderJsonException(BaseException $e)
    {
        $result = [
            'code' => $e->getCode(),
            'message' => $e->getMessage(),
            'data' => '',
        ];

        echo json_encode($result);
    }

    public function renderHtmlException(BaseException $e)
    {
        $data = [
            'message' => $e->getMessage(),
            'trace' => '',
        ];

        if (!$this->app->env('prod')) {
            $data['trace'] = nl2br($e->getTraceAsString());
        }

        View::html('error/index', $data);
    }

    public function getTrace(BaseException $e)
    {
        $traces = $e->getTrace();

        $messages = [];
        foreach ($traces as $trace) {
            $message[] = '';
        }

        return $messages;
    }

}
